package com.yupi.springbootinit.bizmq;

import com.rabbitmq.client.Channel;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.constant.CommonConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.service.ChartService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class BiMessageConsumer {

    @Resource
    private ChartService chartService;

    @Resource
    private AiManager aiManager;

    // 指定程序监听的 消息队列 和 确认机制
    @SneakyThrows
    @RabbitListener(queues = {BiMqConstant.BI_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("receiveMessage message = {}", message);
        if (StringUtils.isBlank(message)){
            // 如果失败，消息拒绝
            channel.basicNack(deliveryTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"消息为空");
        }
        long chartId = Long.parseLong(message);
        Chart chart = chartService.getById(chartId);
        if (chart == null){
            //消息拒绝
            channel.basicNack(deliveryTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"消息为空");
        }
        //更新执行状态为运行状态
        Chart chartRunning = new Chart();
        chartRunning.setId(chart.getId());
        chartRunning.setStatus("running");
        boolean updateRunningResult = chartService.updateById(chartRunning);
        if (!updateRunningResult) {
            //消息拒绝
            channel.basicNack(deliveryTag,false,false);
            handleChartUpdateError(chart.getId(), "更新执行状态为运行状态-失败！");
            return;
        }
        //调用AI根据输入得到ai返回的结果
        String aiManagerResult = aiManager.doChat(CommonConstant.biModel, builderUserInput(chart));
        //aiManagerResult返回的数据有【【【【【作为分隔符.
        String[] splits = aiManagerResult.split("【【【【【");
        if (splits.length < 3) {
            //消息拒绝
            channel.basicNack(deliveryTag,false,false);
            handleChartUpdateError(chart.getId(), "AI生成错误");
            return;
        }
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();
        //更新执行状态为成功状态,并ai生成的图表 和 结论添加到数据库。
        Chart chartSucceed = new Chart();
        chartSucceed.setId(chart.getId());
        chartSucceed.setStatus("succeed");
        chartSucceed.setGenChart(genChart);
        chartSucceed.setGenResult(genResult);
        boolean updateSuccedResult = chartService.updateById(chartSucceed);
        if (!updateSuccedResult) {
            //消息拒绝
            channel.basicNack(deliveryTag,false,false);
            handleChartUpdateError(chart.getId(), "更新执行状态为成功状态-失败！");
        }
        //消息确认
        channel.basicAck(deliveryTag,false);
    }

    private String builderUserInput(Chart chart){
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        String csvData = chart.getChartData();
        //用户输入目标,图表的类型,图表数据
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");
        String finalGoal = goal + " " + "图表类型请用:" + chartType;
        userInput.append(finalGoal).append("\n");
        //压缩后的数据
        userInput.append("表格数据：").append(csvData).append("\n");
        return userInput.toString();
    }
    //处理错误类
    private void handleChartUpdateError(long chartId, String executeMessage) {
        Chart chart = new Chart();
        chart.setId(chartId);
        chart.setStatus("failed");
        chart.setExecMessage(executeMessage);
        boolean updateResult = chartService.updateById(chart);
        if (!updateResult) {
            log.error("更新状态为成功状态失败。失败图表编号为：" + chartId
                    + "错误信息为:" + executeMessage);
        }
    }

}
